package calorie.com.calorie.util;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;

import com.lxh.baselibray.net.ServiceGenerator;
import com.lxh.baselibray.util.ToastUtils;

/**
 * Created by 黄
 * 下载成功广播类
 */
public class DownloadReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            installApk(context, id, PublicUtile.getApkDownPath(context) + PublicUtile.TestApkName);
        } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            //处理 如果还未完成下载，用户点击Notification ，跳转到下载中心
            Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            viewDownloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(viewDownloadIntent);
        }
    }

    /**
     * 启动安装
     *
     * @param context
     * @param downloadApkId
     * @param apkPath
     */
    private static void installApk(Context context, long downloadApkId, String apkPath) {
        if (canDownloadState(context)) {
            DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            Intent install = new Intent(Intent.ACTION_VIEW);
            Uri downloadFileUri = dManager.getUriForDownloadedFile(downloadApkId);
            if (downloadFileUri != null) {
                Log.e("DownloadManager", downloadFileUri.toString());
                install.setDataAndType(Uri.parse("file://" + apkPath), "application/vnd.android.package-archive");
                install.setData(Uri.parse(ServiceGenerator.BASE_URL + ":8089/image/app-release.apk"));//针对华为手机不能启动系统自带的管理器
                install.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                context.startActivity(install);
            } else {
                Log.e("DownloadManager", "download error");
            }
        } else {
            //ToastUtils.showLongToast(context, "手机不支持");
        }
    }

    private static boolean canDownloadState(Context ctx) {
        try {
            int state = ctx.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}